//
//  BSMainInterfaceViewControllerViewController.m
//  SuoSiApp
//
//  Created by zhang on 16/4/6.
//  Copyright © 2016年 Ym. All rights reserved.
//

#import "ViewController.h"
#import "BSBluetoothViewController.h"
#import "BStripleECGViewController.h"
#import "BSECGRootViewController.h"
#import "BSSetingViewController.h"
#import "BSMainInterfaceViewControllerViewController.h"
#import "BSUIDeviceResponseList+BSUIDeviceResponseList_category.h"
#import "FMDB.h"

@interface BSMainInterfaceViewControllerViewController ()<UIAlertViewDelegate>


@property (nonatomic, strong) UIAlertView *noteAlertView;
@property (nonatomic,strong) FMDatabase *db;
@end

@implementation BSMainInterfaceViewControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.mainInterfaceView = [[BSMainInterfaceView alloc]initWithFrame:self.view.bounds];
    

    [self addMode];
    
    [self bindingUUID];
    self.view = self.mainInterfaceView;
    
//    获取这个人  是不是已经绑定了设备
}


//判断是不是已经绑定设备
- (void)bindingUUID{

    [PKRequestManager GetUserDeviceWithuserID:[BSUserSGton userHandle].user_id method:POST finish:^(NSData *data) {
        //            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        BSUIDeviceResponseList *model = [[BSUIDeviceResponseList alloc]init];
        [model dealWithData:data];
        if ([model.Code isEqualToString:@"0"]) {
//          有这个UUID 就可以 接收验证码
            NSString  *uuidString = model.DeviceModel.UUID;
            NSLog(@"%@",uuidString);
            if (uuidString.length > 0) {
                [BSBluetoothSingleton shareBlutooth].uuiduuid = uuidString;
                
#pragma mark 绑定过设备  把 绑定的设备信息 保存在本地
                [self saveDeviceInformation:model];
            }
        }
    } string:NetStr error:^(NSError *error) {
        ;
    }];
    

}
//保存绑定的设备信息
- (void)saveDeviceInformation:(BSUIDeviceResponseList*)model{
    //  创建我们的数据库的路径 同时拼接数据库的文件名称
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"FMDataBase.db"];
    //    NSLog(@">> 地址%@",path);
    
    //  根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    [_db open];

    {
        //用户选择记住密码 需要在本地存储密码
        [_db executeUpdate:@"update  UserInformationlist set UUID = ? where user_id = ?",model.DeviceModel.UUID,[BSUserSGton userHandle].user_loginName];
        [_db executeUpdate:@"update  UserInformationlist set DeviceID = ? where user_id = ?",model.DeviceModel.DeviceID,[BSUserSGton userHandle].user_loginName];
        
    }

}

#pragma mark -- 四种模式
- (void)addMode{
    //    四种模式的跳转
    
    [self.mainInterfaceView.adornModeBT addTarget:self action:@selector(adornMode:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mainInterfaceView.familyModeBT addTarget:self action:@selector(familyMode:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mainInterfaceView.sportModeBT addTarget:self action:@selector(sportMode:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mainInterfaceView.ICUModeBT addTarget:self action:@selector(ICUModeBT:) forControlEvents:(UIControlEventTouchUpInside)];
    
    //    设置 和 登陆 按钮
    [self.mainInterfaceView.settingBTR addTarget:self action:@selector(setting) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mainInterfaceView.settingBTL addTarget:self action:@selector(setting) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mainInterfaceView.exitBTR addTarget:self action:@selector(exitBT) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mainInterfaceView.exitBTL addTarget:self action:@selector(exitBT) forControlEvents:(UIControlEventTouchUpInside)];
}

// 佩戴模式
- (void)adornMode:(UIButton *)button{
    [self buttonClict:button];
    NSString *str = [BSBluetoothSingleton shareBlutooth].uuiduuid;
    if (str && str.length > 0) {
        
        
        if ([BSUserSGton userHandle].isLogin == NO) {
            ViewController *vc = [[ViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            
            //                    开始扫面蓝牙 链接已经绑定的蓝牙
            [[BSBluetoothSingleton shareBlutooth] findBluetoothWithUUID:str];
            
            BStripleECGViewController *ecgVC = [[BStripleECGViewController alloc]init];
            [self.navigationController pushViewController:ecgVC animated:YES];
            
        }
    } else {
        if ([BSUserSGton userHandle].isLogin == NO) {
            ViewController *vc = [[ViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            //        BSBluetoothSingleton *blueHandle = [BSBluetoothSingleton shareBlutooth];
            
            //        BStripleECGViewController *ecgVC = [[BStripleECGViewController alloc]init];
            //        [self.navigationController pushViewController:ecgVC animated:YES];
            
            
            BSBluetoothSingleton *blueHandle = [BSBluetoothSingleton shareBlutooth];
            if (blueHandle.isConnected == YES) {
                NSLog(@"已经连接到蓝牙");
                //    直接跳向主界面
                BStripleECGViewController *ecgVC = [[BStripleECGViewController alloc]init];
                [self.navigationController pushViewController:ecgVC animated:YES];
            } else {
                NSLog(@"佩戴模式");
                
                BSBluetoothViewController *blueVC = [[BSBluetoothViewController alloc]init];
                [self.navigationController pushViewController:blueVC animated:YES];
                
            }
            
        }
        
    }
    
    

    
    
    
    
   
}
//家属模式
- (void)familyMode:(UIButton *)button{

//    [self buttonClict:button];
//        [self showNote];
//    NSLog(@"家属模式");
}
//运动模式
- (void)sportMode:(UIButton *)button{
//    [self buttonClict:button];
//    [self showNote];
//    NSLog(@"运动模式");
}

//监护模式
- (void)ICUModeBT:(UIButton *)button{
//    [self buttonClict:button];
//    [self showNote];
    
}
//设置
- (void)setting{

    NSLog(@"设置");
    
    if ([BSUserSGton userHandle].isLogin == NO) {
        ViewController *vc = [[ViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        BSSetingViewController *setVC = [[BSSetingViewController alloc]init];
        
        setVC.user_id = self.user_id;
        [self.navigationController pushViewController:setVC animated:YES];
    }
}
//退出登陆
- (void)exitBT{
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否退出登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alertView show];

//    [self performSelector:@selector(exitLogin:) withObject:nil afterDelay:2];
    
//    [[BSBluetoothSingleton shareBlutooth] warningForSianalWeak];
    
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [BSUserSGton userHandle].isLogin = NO;
        ViewController *vc = [[ViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];

          } else {
        
    }
}




- (void)buttonClict:(UIButton *)button{
    
    
    if (!_tempBT) {
        
        _tempBT = button;
        
        [button setBackgroundImage:[UIImage imageNamed:@"main_mode_sel.png"] forState:(UIControlStateNormal)];
        
    }else if([_tempBT isEqual:button]){
        
        
    }else{
        
        [_tempBT setBackgroundImage:[UIImage imageNamed:@"main_nor_select.png"] forState:(UIControlStateNormal)];
        [button setBackgroundImage:[UIImage imageNamed:@"main_mode_sel.png"] forState:(UIControlStateNormal)];
        _tempBT = button;
    }
}



- (void)sendRequest:(NSURLRequest *)request finish:(Finish)finish error:(Error)error {
    // 请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (nil == connectionError) {// 请求成功后block调用
            NSLog(@"请求成功");
            finish(data);
        } else {// 请求失败后block调用
            NSLog(@"请求失败");
            error(connectionError);
        }
    }];
    
}

- (void)showNote{

    _noteAlertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该模式正在开发" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [_noteAlertView show];
    [self performSelector:@selector(reportL) withObject:nil afterDelay:1];
    
}

- (void)reportL{
    
    if (_noteAlertView) {
        [_noteAlertView dismissWithClickedButtonIndex:_noteAlertView.cancelButtonIndex animated:YES];
    }
}


- (void)viewWillAppear:(BOOL)animated{

    self.navigationItem.hidesBackButton = YES;
    NSMutableAttributedString *str;
    if ([BSUserSGton userHandle].realName && [BSUserSGton userHandle].realName.length > 1) {
        str =[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"欢迎您登陆, %@",[BSUserSGton userHandle].realName]];
    } else {
        str =[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"欢迎您登陆, %@",[BSUserSGton userHandle].user_loginName]];
    }
    
    //    [str addAttribute:NSForegroundColorAttributeName value:BSBTGreen range:NSMakeRange(str.length - 3,3)];
    self.mainInterfaceView.userLable.attributedText = str;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
